<template>
  <wsPage title="活动列表">
    <div slot="page_operate">
      <Button @click="refresh">
        <Icon type="refresh"></Icon><span>刷新</span>
      </Button>
    </div>
    <wsSmPanel @simple-query="getNavigationList">
      <!-- 筛选查询 -->
      <div slot="query_form">
        <Form
          :model="queryForm"
          :label-width="100"
          inline
          style="width:50%;"
        >
          <!-- <FormItem label="状态">
						<RadioGroup type="button" size="large">
                            <Radio label="3">全部</Radio>
                            <Radio label="0">新增</Radio>
					        <Radio label="1">已上线</Radio>
                            <Radio label="2">已下线</Radio>
					    </RadioGroup>
					</FormItem> -->
          <FormItem label="状态">
            <RadioGroup
              v-model="queryForm.status"
              type="button"
              size="large"
              @on-change="selectStatus"
            >
              <Radio
                :label="item.status"
                v-for="(item,index) in navList"
                :key="index"
              >{{item.name}}</Radio>
            </RadioGroup>
          </FormItem>
          <!-- <FormItem label="时间">
						<Row>
			                <Col span="11">
			                    <FormItem>
			                        <DatePicker type="date" placeholder="开始时间" v-model="queryForm.searchStartTime"></DatePicker>
			                    </FormItem>
			                </Col>
			                <Col span="2" style="text-align: center">——</Col>
			                <Col span="11">
			                    <FormItem>
			                        <DatePicker type="date" placeholder="结束时间" v-model="queryForm.searchEndTime"></DatePicker>
			                    </FormItem>
			                </Col>
			            </Row> 
					</FormItem> -->
          <FormItem label="名称">
            <Input
              v-model="queryForm.name"
              placeholder="请输入"
              style="width:500px;"
            />
          </FormItem>
        </Form>
      </div>
      <!-- 数据列表 -->
      <div slot="list_operate">
        <Select
          class="ws-form-select"
          v-model="queryForm.languageCode"
          @on-change="selectCode"
        >
          <Option
            :value="item.code"
            v-for="(item,index) in fields.languages"
            v-bind:key="index"
          >{{item.motherTongue}}/{{item.english}}</Option>
        </Select>
        <Button @click="addActivities">发布活动</Button>
      </div>
      <!-- content -->
      <div slot="list_data">
        <ws-table
          :data="table.data"
          style="width: 100%"
        >
          <ws-table-column
            label="名称"
            min-width="180"
            align="center"
          >
            <template slot-scope="scope">
              <div v-if="!scope.row.editStatus">{{scope.row.name}}</div>
              <Input
                placeholder="请输入"
                v-if="scope.row.editStatus"
                v-model="editActivityparams.name"
              ></Input>
            </template>
          </ws-table-column>
          <ws-table-column
            label="状态"
            min-width="100"
            align="center"
          >
            <template slot-scope="scope">
              <span>{{scope.row.status == 1?'已上架':scope.row.status == 2 ? '未上架' : '新增'}}</span>
            </template>
          </ws-table-column>
          <ws-table-column
            label="排序"
            min-width="100"
            align="center"
          >
            <template slot-scope="scope">
              <span>{{scope.$index}}</span>
            </template>
          </ws-table-column>
          <ws-table-column
            label="活动图片"
            min-width="230"
            align="center"
          >
            <template slot-scope="scope">
              <img
                :src="scope.row.imgUrl"
                alt=""
                style="width: 100px;height: 100px;"
                v-if=" !scope.row.editStatus"
              />
              <!-- <span
                style="width: 135px;height: 100px;line-height:100px;"
                v-if="scope.row.imgUrl == ''"
              >暂未上传图片</span> -->
              <ws-upload-cos
                ref="coverUpload"
                catelog="goods"
                :show-upload-list="false"
                :format="['jpg','jpeg','png','gif']"
                :max-size="2048"
                :on-success="uploadCoverSuccess"
                :auto-upload="false"
                :on-file-list="uploadCoverFileList"
                v-if="scope.row.editStatus"
              >
                <div
                  class="ws-middle"
                  :style="positionStyle"
                  style="border: 1px solid #ccc;cursor: pointer;"
                >
                  <img
                    :src="scope.row.imgUrl"
                    alt=""
                    :style="positionStyle"
                    v-if="cropper.datas.cover.base64 == ''"
                  >
                  <img
                    :src="cropper.datas.cover.base64"
                    :style="positionStyle"
                    v-if="cropper.datas.cover.base64 != ''"
                  />
                </div>
              </ws-upload-cos>
               <!-- 上传图片 -->
                            <!-- <div :style="{backgroundImage:'url('+scope.row.imgUrl+')',backgroundRepeat:'no-repeat', backgroundPosition:'center center', backgroundSize: '100% auto',width:'100px;',height:'100px;'}"  v-if="scope.row.editStatus"></div>
                            <ws-upload-cos ref="upload" catelog="merchants" :cfile-key="form.upload.fileKey" :show-upload-list="false" :format="['jpg','jpeg','png','gif']" :max-size="2048" :on-success="uploadSuccess" type="drag" v-if="scope.row.editStatus">
                                <Button>添加图片</Button>
                            </ws-upload-cos> -->
            </template>
          </ws-table-column>

          <ws-table-column
            label="活动链接H5"
            min-width="220"
            align="center"
            
          >
            <template slot-scope="scope">

              <div v-if="!scope.row.editStatus">{{scope.row.url}}</div>
              <Input
                placeholder="请输入"
                v-if="scope.row.editStatus"
                v-model="editActivityparams.url"
              ></Input>
            </template>
          </ws-table-column>
          <ws-table-column
            label="语言"
            min-width="180"
            align="center"
          >
            <template slot-scope="scope">
               <Select
          class="ws-form-select"
          v-model="scope.row.languageCode"
          @on-change="selectEditCode(scope.row)"
          disabled
          v-if="!scope.row.editStatus"
        >
          <Option
            :value="item.code"
            v-for="(item,index) in fields.languages"
            v-bind:key="index"
          >{{item.motherTongue}}/{{item.english}}</Option>
        </Select>

        <Select
          class="ws-form-select"
          v-model="editActivityparams.languageCode"
          @on-change="selectEditCode(scope.row)"
          v-if="scope.row.editStatus"
        >
          <Option
            :value="item.code"
            v-for="(item,index) in fields.languages"
            v-bind:key="index"
          >{{item.motherTongue}}/{{item.english}}</Option>
        </Select>
              <!-- <span>{{scope.row.languageCode}}</span> -->
            </template>
          </ws-table-column>
          <ws-table-column
            label="发布时间"
            min-width="180"
            align="center"
          >
            <template slot-scope="scope">
              <span>{{scope.row.createDate}}</span>
            </template>
          </ws-table-column>
          <ws-table-column
            label="操作"
            min-width="180"
            align="center"
          >
            <template slot-scope="scope">
              <Button
                size="small"
                type="text"
                @click="shelf(scope.row)"
                v-if="scope.row.status == 2"
              >上架</Button>
              <Button
                size="small"
                type="text"
                @click="Obtained(scope.row)"
                v-if="scope.row.status == 1"
              >下架</Button>
              <!-- <Button size="small" type="text" @click="moveUp(scope.row)" v-if="queryForm.selfStatus==2">上移</Button> -->
              <!-- <Button size="small" type="text" @click="moveDown(scope.row)" v-if="queryForm.selfStatus==2">下移</Button> -->
              <!-- <Button size="small" type="text" @click="goTop(scope.row)" v-if="queryForm.selfStatus==2">置顶</Button> -->
              <Button
                size="small"
                type="text"
                @click="editActivity(scope.row)"
                v-if="!scope.row.editStatus"
              >修改</Button>
              <Button
                @click="confirm(scope.row)"
                type="text"
                size="small"
                v-if="scope.row.editStatus"
              >确认修改</Button>
              <Button
                @click="cancel(scope.row)"
                type="text"
                size="small"
                v-if="scope.row.editStatus"
              >取消修改</Button>
              <Button
                size="small"
                type="text"
                @click="deleteActivity(scope.row)"
              >删除</Button>
            </template>
          </ws-table-column>
        </ws-table>
      </div>
    </wsSmPanel>
    <ws-cropper v-model="cropper.show" :img="cropper.imgData" :config="cropper.config" @crop-ok="cropOk"></ws-cropper>
  </wsPage>
</template>
<script>
import Util from "../../../common/util.js";
import FileUtil from "../../../common/file.js";
import Common from "../../../common/common.js";
import $ from "jquery";
export default {
  data() {
    return {
      form: {
                upload: {
                    fileKey: "",
                    imgData:''
                }
            },
      cropper: {
        show: false,
        datas: {
          top: {
            base64: ""
          },
          cover: {
            base64: ""
          }
        },
        config: {
          fixedNumber: [1, 1],
          // 只有自动截图开启 宽度高度才生效
          autoCropWidth: 100,
          autoCropHeight: 100
        }
      },
      editActivityparams: {
        id: 0,
        name: "",
        url: "",
        imgUrl: "",
        languageCode:''
      },
      navList: [
        {
          name: "新增",
          status: 0
        },
        {
          name: "已上线",
          status: 1
        },
        {
          name: "未上线",
          status: 2
        }
      ],
      // 条件查询
      queryForm: {
        // selfStatus: "1", //上架号码
        type: "", //类型
        languageCode: "zh",
        status: 1, //0=新增 1=已上架  2=已下架 3=全部
        name: "" //导航名称
      },
      queryPanel: {
        fields: {
          brands: []
        },
        model: {
          name: "",
          status: "2",
          promotionStatus: "",
          saleType: "",
          shop: "",
          brandId: ""
        }
      },
      table: {
        data: [],
        page: {
          total: 0, //总条数
          pageNum: 1, //当前页
          pageSize: 10 //每页显示条数
        },
        selection: [] //选中
      },
      // 语言类型
      fields: {
        languages: []
      }
    };
  },
  computed: {
    positionStyle() {
      return (
        "width:" +
        this.cropper.config.autoCropWidth +
        "px;height:" +
        this.cropper.config.autoCropHeight +
        "px;"
      );
    }
  },
  watch:{
    'editActivityparams':function(newVal,oldVal){
      console.log(newVal)
    }
  },
  mounted() {
    this.init();
  },
  methods: {
    selectEditCode(){

    },
    //刷新
    refresh() {
      this.cropper ={
        show: false,
        datas: {
          top: {
            base64: ""
          },
          cover: {
            base64: ""
          }
        },
        config :{
          fixedNumber: [1, 1],
          // 只有自动截图开启 宽度高度才生效
          autoCropWidth: 100,
          autoCropHeight: 100
        }
      };
      this.editActivityparams = {
        id: 0,
        name: "",
        url: "",
        imgUrl: ""
      },
      this.queryForm={
        // selfStatus: "1", //上架号码
        // type: "", //类型
        languageCode: "zh",
        status: 1, //0=新增 1=已上架  2=已下架 3=全部
        name: "" //导航名称
      };
      this.table.data = [];
      this.table.page.total = 0; //总条数
      this.table.page.pageNum = 1; //当前页
      this.table.page.pageSize = 10; //每页显示条数
      // this.table.selection = []; //选中
      this.init();
    },
    editActivity(row) {
      let _row = row;
      // console.log(_row);
      if (this.editActivityparams.id == 0) {
        _row.editStatus = !_row.editStatus;
        this.editActivityparams.id = _row.id;
        this.editActivityparams.imgUrl = _row.imgUrl;
        this.editActivityparams.name = _row.name;
        this.editActivityparams.url = _row.url;
        this.editActivityparams.languageCode = _row.languageCode;
      }
    },
    //取消修改
    cancel(row) {
      this.editActivityparams = {
        id: 0,
        name: "",
        url: "",
        imgUrl: "",
        languageCode: ''
      };
        this.cropper = {
          show: false,
          datas: {
            top: {
              base64: ""
            },
            cover: {
              base64: ""
            }
          },
          config: {
            fixedNumber: [1, 1],
            // 只有自动截图开启 宽度高度才生效
            autoCropWidth: 100,
            autoCropHeight: 100
          }
        };
      if (row) row.editStatus = !row.editStatus;
    },
    /**
                提交验证数据
             */
    confirm(row) {
      var _this = this;
      let imgUrl = _this.cropper.datas.cover.base64;
      //   let name = _this.editData.productName;
      // let orderNum=_this.addBannerData.orderNum;
      // let type=_this.addBannerData.type;
      // let languageCode=_this.addBannerData.languageCode;
      // let selectionList=_this.addBannerData.selectionList;
      // if(Util.vad.isBlank(imgUrl)){
      //     this.$Message.info('请上传图片');
      // 	return;
      // }
      //   if (Util.vad.isBlank(name)) {
      //     this.$Message.info("请输入商店名称");
      //     return;
      //   }
      this.contentDataConfirm(row);
    },
    /**
     * 内容验证不能为空
     */
    contentDataConfirm(row) {
      var _this = this;
      _this.saveCoverImg(row);
    },
    /**
     * 封面图上传成功
     */
    uploadCoverSuccess(response, file, fileList) {
      let _this = this;
      // var imgurl = '';
      console.log(this.editActivityparams);
      var params = {
        // id : this.editActivityparams.id,
        imgUrl: this.editActivityparams.imgUrl,
        name: this.editActivityparams.name,
        url: this.editActivityparams.url,
        languageCode : this.editActivityparams.languageCode
      };
      console.log(params);
      // debugger
      if (0 == response.meta.code) {
        params.imgUrl = response.data.Location;
        _this.editActivityparams.imgUrl = response.data.Location;
        this.axios.put("/ws/ops/product/updateNavigation/" + this.editActivityparams.id, params).then(response => {
          var res = response.data;
          var resMeta = res.meta;
          if (0 == resMeta.code) {
            _this.$Message.info("修改成功!");
            _this.getNavigationList();
            _this.cancel(); 
          } else {
            _this.$Message.warning("修改失败");
          }
        });
      }
    },
    /**
     * 截图OK
     */
    cropOk(data) {
      let action = data.action;
      let imgBase64Data = data.data;
      this.cropper.datas.cover.base64 = imgBase64Data;
      this.cropper.imgData = data;
      // console.log(this.editActivityparams)
    },
    /**
     * 添加顶部图片
     */
    addTopImg(result) {
      this.cropper.imgData = result;
      this.cropper.show = true;
    },
    /**
     * 保存封面图
     */
    saveCoverImg(row) {
      let _this = this; 
      if (this.cropper.datas.cover.base64 != "") {
        let data = this.cropper.datas.cover.base64;
        let fileName = "activity_" + new Date().getTime() + ".jpg";
        let newFile = FileUtil.dataURLtoFile(data, fileName);
        // console.log(this.$refs.coverUpload.execUpload);
        this.$refs.coverUpload.execUpload([newFile]);
        // this.editData.productImgUrl = fileName;
      }
      console.log(row);
      console.log(this.editActivityparams)
      if (row.imgUrl == this.editActivityparams.imgUrl) {
        let params = {
          name: this.editActivityparams.name,
          imgUrl: this.editActivityparams.imgUrl,
          url: this.editActivityparams.url,
          languageCode : this.editActivityparams.languageCode
        };
        this.axios
          .put("/ws/ops/product/updateNavigation/" + row.id, params)
          .then(response => {
            var res = response.data;
            var resMeta = res.meta;
            if (0 == resMeta.code) {
              _this.$Message.info("修改成功!");
              _this.getNavigationList();
              _this.cancel();
            } else {
              _this.$Message.warning("修改失败");
            }
          });
      }
    },
    /**
     * 封面图片
     */
    uploadCoverFileList(fileList) {
      let _this = this;
      let newFile = fileList[0];
      FileUtil.readFile(newFile, function(result, currFile) {
        _this.addTopImg(result);
      });
    },
    init() {
      this.initLanguages();
      this.getNavigationList();
    },
    shelf(_row) {
      let _this = this;
      _this.axios
        .put("/ws/ops/product/uppShelfNavigation/" + _row.id)
        .then(response => {
          let res = response.data;
          let resMeta = res.meta;
          if (0 == resMeta.code) {
            _this.$Message.info("上架活动导航成功");
            // 重新调用bannerlist接口
            _this.getNavigationList();
          } else {
            _this.$Message.warning(resMeta.message);
          }
        });
      //   this.$confirm({
      //     title: "操作提示",
      //     width: 300,
      //     content: "你确认下架选中的活动导航吗?",
      //     onOk: function() {
      //       _this.makeSureDownActivity(_row.id);
      //     }
      //   });
    },
    Obtained(_row) {
      let _this = this;
      this.$confirm({
        title: "操作提示",
        width: 300,
        content: "你确认下架选中的活动导航吗?",
        onOk: function() {
          _this.makeSureDownActivity(_row.id);
        }
      });
    },
    deleteActivity(_row) {
      let _this = this;
      this.$confirm({
        title: "操作提示",
        width: 300,
        content: "你确认删除选中的活动导航吗?",
        onOk: function() {
          _this.makeSureDeleteActivity(_row.id);
        }
      });
    },
    makeSureDownActivity(id) {
      let _this = this;
      _this.axios
        .put("/ws/ops/product/lowShelfNavigation/" + id)
        .then(response => {
          let res = response.data;
          let resMeta = res.meta;
          if (0 == resMeta.code) {
            _this.$Message.info("下架活动导航成功");
            // 重新调用bannerlist接口
            _this.getNavigationList();
            _this.cancel();
          } else {
            _this.$Message.warning(resMeta.message);
          }
        });
    },
    makeSureDeleteActivity(id) {
      let _this = this;
      this.axios
        .delete("/ws/ops/product/delNavigation/" + id)
        .then(response => {
          let res = response.data;
          let resMeta = res.meta;
          if (0 == resMeta.code) {
            _this.$Message.info("删除活动导航成功");
            // 重新调用bannerlist接口
            _this.getNavigationList();
            _this.cancel();
          } else {
            _this.$Message.warning(resMeta.message);
          }
        });
    },
    selectCode() {
      this.getNavigationList();
    },
    selectStatus() {
      // let type = this.queryForm.status;
      this.table.page.pageNum = 1;
      this.table.page.pageSize = 10;
      this.table.page.total = 0;
      this.getNavigationList();
    },
    /*
     * 获取导航列表
     */
    getNavigationList() {
      let _this = this;
      let params = {
        pageNum: this.table.page.pageNum,
        pageSize: this.table.page.pageSize,
        status: this.queryForm.status,
        name: this.queryForm.name,
        languageCode:this.queryForm.languageCode
      };

      this.axios
        .get(
          "/ws/ops/discount/listNaviProducts/" +
            params.pageSize +
            "/" +
            params.pageNum +
            "?status=" +
            params.status +
            "&name=" +
            params.name +
            "&languageCode=" +
            params.languageCode
        )
        .then(function(response) {
          let res = response.data;
          let resMeta = res.meta;
          if (0 == resMeta.code) {
            if (res.data.list.length > 0) {
              res.data.list.forEach(function(v) {
                v.editStatus = false;
              });
            }
            _this.table.data = res.data.list;
            _this.table.page.total = res.data.total;
            if (res.data.pageNum > 1) {
              _this.table.page.pageNum = res.data.pageNum;
            } else {
              _this.table.page.pageNum = 1;
            }
            _this.table.page.pageSize = res.data.pageSize;
          } else {
            _this.$Message.warning(resMeta.message);
          }
        });
    },
    /**
     * 加载翻译语言列表
     */
    initLanguages() {
      const _this = this;
      this.axios.get("/ws/ops/v2/languages/translatable").then(response => {
        var res = response.data;
        var resMeta = res.meta;
        if (0 == resMeta.code) {
          _this.fields.languages = res.data;
        } else {
          _this.$Message.warning(resMeta.message);
        }
      });
    },
    /**
     * 发布活动
     */
    addActivities() {
      this.$router.push("/activities/addActivities");
    }
  }
};
</script>

<style>
</style>
